import { WEEK_DAYS, formatDate } from '../../utils/util'

// 获取当前时间的前后n天
export function getPastAndFutureDates(startDate, num = 14) {
  const currentDate = startDate || new Date()
  const pastDates = []
  const futureDates = []

  // 获取过去的日期
  for (let i = num; i >= 1; i--) {
    const pastDate = new Date(currentDate)
    pastDate.setDate(currentDate.getDate() - i)
    pastDates.push(pastDate)
  }

  // 获取未来的日期
  for (let i = 1; i <= num; i++) {
    const futureDate = new Date(currentDate)
    futureDate.setDate(currentDate.getDate() + i)
    futureDates.push(futureDate)
  }

  return {
    pastDates: pastDates,
    futureDates: futureDates
  };
}

// 生成头部日历数据
export function generateDates(startDate) {
  const date = startDate || new Date()
  const year = date.getFullYear()
  const { futureDates, pastDates } = getPastAndFutureDates(date)
  pastDates.push(date)

  const dateArray = []
  const allDates = [...pastDates, ...futureDates]

  for (let i = 0; i < allDates.length; i++) {
    const item = allDates[i]
    const weekIndex = item.getDay()
    const month = item.getMonth() + 1
    const currentDate = item.getDate()

    dateArray.push({
      date: `${month}-${currentDate}`,
      week: WEEK_DAYS[weekIndex],
      origin: `${year}-${String(month).padStart(2, '0')}-${currentDate}`,
    })
  }

  return dateArray
}

// 将yyyy-mm-hh转为new Date对象
export function parseDateString(dateString) {
  const dateParts = dateString.split('-')
  const year = parseInt(dateParts[0], 10)
  const month = parseInt(dateParts[1], 10)
  const day = parseInt(dateParts[2], 10)

  return new Date(year, month - 1, day)
}

export function getCurrentDate(dates = generateDates()) {
  return dates.filter((item) => item.origin === formatDate(new Date()))
}